
import time

class SnowFlake:
    def __init__(self, machine_id):
        self.machine_id = machine_id  # 从settings.py读取‌:ml-citation{ref="1" data="citationList"}
        self.sequence = 0
        self.last_timestamp = -1

    def generate_id(self):
        # 生成时间戳
        timestamp = int(time.time() * 1000)
        # 如果时间戳小于上一次的时间戳，抛出异常
        if timestamp < self.last_timestamp:
            raise Exception("时间戳异常")
        # 如果时间戳等于上一次的时间戳，序列号加1
        if timestamp == self.last_timestamp:
            self.sequence = (self.sequence + 1) & 0xFFF
            # 如果序列号等于0，等待下一个毫秒
            if self.sequence == 0:
                timestamp = self._wait_next_millis()
        else:
            # 否则，序列号置为0
            self.sequence = 0
        # 更新上一次的时间戳
        self.last_timestamp = timestamp
        # 返回ID
        return 0 | (timestamp << 22) | (self.machine_id << 12) | self.sequence
